package com.urule.utils;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectWriter;
import org.codehaus.jackson.map.SerializerProvider;


public class JsonUtils {
	
	public static String toJSON(Object object) throws IOException {
		ObjectMapper mapper=getObjectMapper();
		ObjectWriter objectWriter = mapper.writerWithDefaultPrettyPrinter();
		return objectWriter.writeValueAsString(object);
	}

	public static <T> T fromJSON(String data, Class<T> clazz) throws Exception {
		return getObjectMapper().readValue(data, clazz);
	}

	public static ObjectMapper getObjectMapper() {
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		// 设置返回null转为 空字符串""
		mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
			@Override
			public void serialize(Object paramT, JsonGenerator paramJsonGenerator,
					SerializerProvider paramSerializerProvider) throws IOException {
				paramJsonGenerator.writeString("");
			}
		});
		return mapper;
	}

}
